﻿using System.Drawing;
using System.Text;
using FortuneArterial.Core.Diagnostics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FortuneArterial.Core.IO;

namespace FortuneArterial.Site.Laboratory.Controllers
{
    public class PhantomJSController
        : BaseController
    {
        public ActionResult Index()
        {
            return SmartView();
        }

        [HttpGet]
        [DisplayName("网页截图")]
        public ActionResult ScreenCapture()
        {
            return SmartView();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ScreenCapture(string url, string html, string options)
        {
            //生成临时文件名
            var fileName = Path.GetRandomFileName();

            var mapPath = Server.MapPath("~");
            var phantomPath = Path.Combine(mapPath, @"Assets\PhantomJS\");

            var htmlUrlPath = string.Format("/temp/ScreenShot/HTML/{0}.html", fileName);
            var pngUrlPath = string.Format("/temp/ScreenShot/PNG/{0}.png", fileName);

            var htmlFile = Server.MapPath("~" + htmlUrlPath);
            var captureFile = Server.MapPath("~" + pngUrlPath);

            var htmlUrl = string.Format("{0}://{1}:{2}{3}{4}",
                    Request.Url.Scheme,
                    Request.Url.Host,
                    Request.Url.Port,
                    Request.ApplicationPath,
                    htmlUrlPath);
            var pngUrl = string.Format("{0}://{1}:{2}{3}{4}",
                    Request.Url.Scheme,
                    Request.Url.Host,
                    Request.Url.Port,
                    Request.ApplicationPath,
                    pngUrlPath);

            DirectoryHelper.CreateDirectory(htmlFile);
            DirectoryHelper.CreateDirectory(captureFile);

            if (!string.IsNullOrEmpty(html))
            {
                //将html写入临时文件
                System.IO.File.WriteAllText(htmlFile, html, Encoding.UTF8);
            }

            var msg = ProcessHelper.ExecuteCommand(
                Path.Combine(phantomPath, @"phantomjs.exe"),
                string.Format(@" {0} '{1}' {2} {3}", 
                    Path.Combine(phantomPath, @"rasterize.js"),
                    htmlUrl,
                    captureFile,
                    options));

            return Json(new { Result = true, Message = msg, ImageUrl = pngUrl });
        }
    }
}
